import axios from 'axios'
import { Md5 } from 'ts-md5/dist/md5'
const baseLocationUrl = window.location.origin ? window.location.origin : 
 window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '')
const envType: string =  process.env.NODE_ENV === 'development' ? '/api' : ''
const http = axios.create({
    baseURL: baseLocationUrl + envType, 
    timeout: 5000
})

http.interceptors.request.use((config) => {
    config.data.time = (Date.parse(new Date() as any) / 1000).toString();
    config.data.userId = config.data.userId ? config.data.userId : (window as any).user_id
    config.data.token = config.data.token ? config.data.token : (window as any).userToken
    const sign = EncryptedCharacter(config.data)
    config.data.sign = Md5.hashStr(sign)
    return config
})

// http.interceptors.response.use((res) => {})

interface RequestParams {
    method: string,
    url: string,
    data: Record<string, unknown>
}

function reverse(arys: Record<string, unknown>) {
    const newkey: string[] = Object.keys(arys).sort().reverse();
    const newObj: Record<string, unknown> = {};
    for (let i = 0; i < newkey.length; i++) {
      newObj[newkey[i]] = arys[newkey[i]];
    }
    return newObj;
}

function EncryptedCharacter(arys: Record<string, unknown>) {
    const param = reverse(arys);
    const extra_str = "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
    if (Object.prototype.toString.call(param) !== '[object Object]') {
        return '';
    }
    let queryParam = '';
    for (const key in param) {
        if (key in param) {
            const value: any = param[key];
            queryParam += toQueryPair(key, value);
        }
    }
    return queryParam.slice(1) + extra_str;
}


function toQueryPair(key: string, value: string) {
    if (typeof value == 'undefined') {
        return `&${key}=`;
    }
    return `&${key}=${value}`;
}
const request = (requestData: RequestParams) => {
    return http(requestData)
}

export default request